<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Settlement;
use App\Models\Task;
use Faker\Factory as Faker;

class SettlementSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create('zh_CN');

        // 获取可用的任务列表
        $tasks = Task::all();
        
        if ($tasks->isEmpty()) {
            $this->command->info('没有找到任务，跳过创建结算单...');
            return;
        }

        $landingCompanies = [
            '北京科技有限公司',
            '上海商务咨询公司', 
            '广州数据服务公司',
            '深圳智能科技公司',
            '杭州网络技术公司',
            '南京软件开发公司',
            '成都信息技术公司',
            '武汉电子商务公司'
        ];

        $statuses = [
            Settlement::STATUS_PENDING_TAX,
            Settlement::STATUS_PENDING_SUBMIT,
            Settlement::STATUS_DISTRIBUTING, 
            Settlement::STATUS_COMPLETED,
            Settlement::STATUS_CANCELLED,
            Settlement::STATUS_DISTRIBUTE_FAILED,
            Settlement::STATUS_PARTIAL_FAILED
        ];

        // 创建30个结算单
        for ($i = 0; $i < 30; $i++) {
            $task = $faker->randomElement($tasks);
            $status = $faker->randomElement($statuses);
            
            // 生成基础数据
            $totalCount = $faker->numberBetween(50, 500);
            $totalAmount = $faker->randomFloat(2, 5000, 100000);
            
            // 根据状态生成成功数据
            switch ($status) {
                case Settlement::STATUS_COMPLETED:
                    $successRate = $faker->randomFloat(2, 95, 100);
                    break;
                case Settlement::STATUS_DISTRIBUTING:
                    $successRate = $faker->randomFloat(2, 60, 90);
                    break;
                case Settlement::STATUS_PARTIAL_FAILED:
                    $successRate = $faker->randomFloat(2, 40, 80);
                    break;
                case Settlement::STATUS_DISTRIBUTE_FAILED:
                    $successRate = $faker->randomFloat(2, 0, 30);
                    break;
                case Settlement::STATUS_CANCELLED:
                    $successRate = 0;
                    break;
                default:
                    $successRate = 0;
                    break;
            }

            
            $successCount = (int)($totalCount * ($successRate / 100));
            $successAmount = $totalAmount * ($successRate / 100);
            
            $createdAt = $faker->dateTimeBetween('-6 months', 'now');
            
            $settlement = Settlement::create([
                'settlement_name' => $task->name . '-' . date('Y年m月', $createdAt->getTimestamp()) . '结算单',
                'tenant_id' => $task->tenant_id,
                'task_id' => $task->id,
                'landing_company' => $faker->randomElement($landingCompanies),
                'total_amount' => $totalAmount,
                'total_required_balance' => $totalAmount,
                'success_amount' => $successAmount,
                'total_count' => $totalCount,
                'success_count' => $successCount,
                'status' => $status,
                'deliverables' => $faker->optional(0.8)->paragraph(2),
                'remarks' => $faker->optional(0.6)->sentence,
                'uploaded_files' => $faker->optional(0.7)->passthrough([
                    [
                        'name' => '结算明细表.xlsx',
                        'size' => $faker->numberBetween(50000, 500000),
                        'path' => '/uploads/settlements/' . $faker->uuid . '.xlsx'
                    ],
                    [
                        'name' => '发放凭证.pdf', 
                        'size' => $faker->numberBetween(100000, 1000000),
                        'path' => '/uploads/settlements/' . $faker->uuid . '.pdf'
                    ]
                ]),
                'created_by' => 1,
                'created_at' => $createdAt,
            ]);

            // 根据状态设置相应的时间戳
            $updates = [];
            switch ($status) {
                case Settlement::STATUS_DISTRIBUTING:
                    $updates['submitted_at'] = $faker->dateTimeBetween($createdAt, 'now');
                    $updates['submitted_by'] = 1;
                    $updates['distribute_started_at'] = $faker->dateTimeBetween($updates['submitted_at'], 'now');
                    break;
                    
                case Settlement::STATUS_COMPLETED:
                    $submittedAt = $faker->dateTimeBetween($createdAt, 'now');
                    $distributeStartedAt = $faker->dateTimeBetween($submittedAt, 'now');
                    $updates['submitted_at'] = $submittedAt;
                    $updates['submitted_by'] = 1;
                    $updates['distribute_started_at'] = $distributeStartedAt;
                    $updates['completed_at'] = $faker->dateTimeBetween($distributeStartedAt, 'now');
                    break;
                    
                case Settlement::STATUS_CANCELLED:
                    $updates['submitted_at'] = $faker->optional(0.7)->dateTimeBetween($createdAt, 'now');
                    if ($updates['submitted_at']) {
                        $updates['submitted_by'] = 1;
                    }
                    break;
                    
                case Settlement::STATUS_DISTRIBUTE_FAILED:
                case Settlement::STATUS_PARTIAL_FAILED:
                    $submittedAt = $faker->dateTimeBetween($createdAt, 'now');
                    $updates['submitted_at'] = $submittedAt;
                    $updates['submitted_by'] = 1;
                    $updates['distribute_started_at'] = $faker->dateTimeBetween($submittedAt, 'now');
                    break;
            }
            
            if (!empty($updates)) {
                $settlement->update($updates);
            }
        }

        $this->command->info('SettlementSeeder completed successfully!');
        $this->command->info('Created 30 settlement records with various statuses.');
    }
}
